{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 快速上手"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "快来使用 🤗 Transformers 吧！无论你是开发人员还是日常用户，这篇快速上手教程都将帮助你入门并且向你展示如何使用 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 进行推理，使用 [AutoClass](https://huggingface.co/docs/transformers/main/zh/./model_doc/auto) 加载一个预训练模型和预处理器，以及使用 PyTorch 或 TensorFlow 快速训练一个模型。如果你是一个初学者，我们建议你接下来查看我们的教程或者[课程](https://huggingface.co/course/chapter1/1)，来更深入地了解在这里介绍到的概念。\n",
    "\n",
    "在开始之前，确保你已经安装了所有必要的库：\n",
    "\n",
    "```bash\n",
    "!pip install transformers datasets evaluate accelerate\n",
    "```\n",
    "\n",
    "你还需要安装喜欢的机器学习框架：\n",
    "\n",
    "\n",
    "```bash\n",
    "pip install torch\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "hide_input": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/tiZFewofSLM?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#@title\n",
    "from IPython.display import HTML\n",
    "\n",
    "HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/tiZFewofSLM?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 是利用预训练模型进行推理的最简单的方式。你能够将 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 开箱即用地用于跨不同模态的多种任务。来看看它支持的任务列表：\n",
    "\n",
    "| **任务**                     | **描述**                            | **模态**        | **Pipeline**                       |\n",
    "|------------------------------|-----------------------------------|-----------------|-----------------------------------------------|\n",
    "| 文本分类                      | 为给定的文本序列分配一个标签                    | NLP             | pipeline(task=\"sentiment-analysis\")           |\n",
    "| 文本生成                      | 根据给定的提示生成文本                       | NLP             | pipeline(task=\"text-generation\")              |\n",
    "| 命名实体识别                  | 为序列里的每个 token 分配一个标签（人, 组织, 地址等等） | NLP             | pipeline(task=\"ner\")                          |\n",
    "| 问答系统                      | 通过给定的上下文和问题, 在文本中提取答案             | NLP             | pipeline(task=\"question-answering\")           |\n",
    "| 掩盖填充                      | 预测出正确的在序列中被掩盖的token               | NLP             | pipeline(task=\"fill-mask\")                    |\n",
    "| 文本摘要                      | 为文本序列或文档生成总结                      | NLP             | pipeline(task=\"summarization\")                |\n",
    "| 文本翻译                      | 将文本从一种语言翻译为另一种语言                  | NLP             | pipeline(task=\"translation\")                  |\n",
    "| 图像分类                      | 为图像分配一个标签                         | Computer vision | pipeline(task=\"image-classification\")         |\n",
    "| 图像分割                      | 为图像中每个独立的像素分配标签（支持语义、全景和实例分割）     | Computer vision | pipeline(task=\"image-segmentation\")           |\n",
    "| 目标检测                      | 预测图像中目标对象的边界框和类别                  | Computer vision | pipeline(task=\"object-detection\")             |\n",
    "| 音频分类                      | 给音频文件分配一个标签                       | Audio           | pipeline(task=\"audio-classification\")         |\n",
    "| 自动语音识别                   | 将音频文件中的语音提取为文本                    | Audio           | pipeline(task=\"automatic-speech-recognition\") |\n",
    "| 视觉问答                      | 给定一个图像和一个问题，正确地回答有关图像的问题          | Multimodal      | pipeline(task=\"vqa\")                          |\n",
    "\n",
    "创建一个 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 实例并且指定你想要将它用于的任务，就可以开始了。你可以将 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 用于任何一个上面提到的任务，如果想知道支持的任务的完整列表，可以查阅 [pipeline API 参考](https://huggingface.co/docs/transformers/main/zh/./main_classes/pipelines)。不过, 在这篇教程中，你将把 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 用在一个情感分析示例上："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import pipeline\n",
    "\n",
    "classifier = pipeline(\"sentiment-analysis\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 会下载并缓存一个用于情感分析的默认的[预训练模型](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english)和分词器。现在你可以在目标文本上使用 `classifier` 了："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'label': 'POSITIVE', 'score': 0.9998}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "classifier(\"We are very happy to show you the 🤗 Transformers library.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果你有不止一个输入，可以把所有输入放入一个列表然后传给[pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline)，它将会返回一个字典列表："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "label: POSITIVE, with score: 0.9998\n",
       "label: NEGATIVE, with score: 0.5309"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results = classifier([\"We are very happy to show you the 🤗 Transformers library.\", \"We hope you don't hate it.\"])\n",
    "for result in results:\n",
    "    print(f\"label: {result['label']}, with score: {round(result['score'], 4)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 也可以为任何你喜欢的任务遍历整个数据集。在下面这个示例中，让我们选择自动语音识别作为我们的任务："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from transformers import pipeline\n",
    "\n",
    "speech_recognizer = pipeline(\"automatic-speech-recognition\", model=\"facebook/wav2vec2-base-960h\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "加载一个你想遍历的音频数据集（查阅 🤗 Datasets [快速开始](https://huggingface.co/docs/datasets/quickstart#audio) 获得更多信息）。比如，加载 [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) 数据集："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datasets import load_dataset, Audio\n",
    "\n",
    "dataset = load_dataset(\"PolyAI/minds14\", name=\"en-US\", split=\"train\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你需要确保数据集中的音频的采样率与 [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h) 训练用到的音频的采样率一致："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = dataset.cast_column(\"audio\", Audio(sampling_rate=speech_recognizer.feature_extractor.sampling_rate))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当调用 `\"audio\"` 列时, 音频文件将会自动加载并重采样。\n",
    "从前四个样本中提取原始波形数组，将它作为列表传给 pipeline："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['I WOULD LIKE TO SET UP A JOINT ACCOUNT WITH MY PARTNER HOW DO I PROCEED WITH DOING THAT', \"FODING HOW I'D SET UP A JOIN TO HET WITH MY WIFE AND WHERE THE AP MIGHT BE\", \"I I'D LIKE TOY SET UP A JOINT ACCOUNT WITH MY PARTNER I'M NOT SEEING THE OPTION TO DO IT ON THE AP SO I CALLED IN TO GET SOME HELP CAN I JUST DO IT OVER THE PHONE WITH YOU AND GIVE YOU THE INFORMATION OR SHOULD I DO IT IN THE AP AND I'M MISSING SOMETHING UQUETTE HAD PREFERRED TO JUST DO IT OVER THE PHONE OF POSSIBLE THINGS\", 'HOW DO I THURN A JOIN A COUNT']"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = speech_recognizer(dataset[:4][\"audio\"])\n",
    "print([d[\"text\"] for d in result])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对于输入非常庞大的大型数据集（比如语音或视觉），你会想到使用一个生成器，而不是一个将所有输入都加载进内存的列表。查阅 [pipeline API 参考](https://huggingface.co/docs/transformers/main/zh/./main_classes/pipelines) 来获取更多信息。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 在 pipeline 中使用另一个模型和分词器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 可以容纳 [Hub](https://huggingface.co/models) 中的任何模型，这让 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 更容易适用于其他用例。比如，你想要一个能够处理法语文本的模型，就可以使用 Hub 上的标记来筛选出合适的模型。靠前的筛选结果会返回一个为情感分析微调的多语言的 [BERT 模型](https://huggingface.co/nlptown/bert-base-multilingual-uncased-sentiment)，你可以将它用于法语文本："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_name = \"nlptown/bert-base-multilingual-uncased-sentiment\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用 `AutoModelForSequenceClassification` 和 `AutoTokenizer` 来加载预训练模型和它关联的分词器（更多信息可以参考下一节的 `AutoClass`）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer, AutoModelForSequenceClassification\n",
    "\n",
    "model = AutoModelForSequenceClassification.from_pretrained(model_name)\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 中指定模型和分词器，现在你就可以在法语文本上使用 `classifier` 了："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'label': '5 stars', 'score': 0.7273}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "classifier = pipeline(\"sentiment-analysis\", model=model, tokenizer=tokenizer)\n",
    "classifier(\"Nous sommes très heureux de vous présenter la bibliothèque 🤗 Transformers.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果你没有找到适合你的模型，就需要在你的数据上微调一个预训练模型了。查看 [微调教程](https://huggingface.co/docs/transformers/main/zh/./training) 来学习怎样进行微调。最后，微调完模型后，考虑一下在 Hub 上与社区 [分享](https://huggingface.co/docs/transformers/main/zh/./model_sharing) 这个模型，把机器学习普及到每一个人! 🤗"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## AutoClass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "hide_input": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/AhChOFRegn4?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#@title\n",
    "from IPython.display import HTML\n",
    "\n",
    "HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/AhChOFRegn4?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在幕后，是由 `AutoModelForSequenceClassification` 和 `AutoTokenizer` 一起支持你在上面用到的 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline)。[AutoClass](https://huggingface.co/docs/transformers/main/zh/./model_doc/auto) 是一个能够通过预训练模型的名称或路径自动查找其架构的快捷方式。你只需要为你的任务选择合适的 `AutoClass` 和它关联的预处理类。\n",
    "\n",
    "让我们回过头来看上一节的示例，看看怎样使用 `AutoClass` 来重现使用 [pipeline()](https://huggingface.co/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 的结果。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### AutoTokenizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分词器负责预处理文本，将文本转换为用于输入模型的数字数组。有多个用来管理分词过程的规则，包括如何拆分单词和在什么样的级别上拆分单词（在 [分词器总结](https://huggingface.co/docs/transformers/main/zh/./tokenizer_summary) 学习更多关于分词的信息）。要记住最重要的是你需要实例化的分词器要与模型的名称相同, 来确保和模型训练时使用相同的分词规则。\n",
    "\n",
    "使用 `AutoTokenizer` 加载一个分词器:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "\n",
    "model_name = \"nlptown/bert-base-multilingual-uncased-sentiment\"\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将文本传入分词器："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input_ids': [101, 11312, 10320, 12495, 19308, 10114, 11391, 10855, 10103, 100, 58263, 13299, 119, 102],\n",
       " 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n",
       " 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "encoding = tokenizer(\"We are very happy to show you the 🤗 Transformers library.\")\n",
    "print(encoding)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分词器返回了含有如下内容的字典:\n",
    "\n",
    "* [input_ids](https://huggingface.co/docs/transformers/main/zh/./glossary#input-ids)：用数字表示的 token。\n",
    "* [attention_mask](https://huggingface.co/docs/transformers/main/zh/.glossary#attention-mask)：应该关注哪些 token 的指示。\n",
    "\n",
    "分词器也可以接受列表作为输入，并填充和截断文本，返回具有统一长度的批次："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pt_batch = tokenizer(\n",
    "    [\"We are very happy to show you the 🤗 Transformers library.\", \"We hope you don't hate it.\"],\n",
    "    padding=True,\n",
    "    truncation=True,\n",
    "    max_length=512,\n",
    "    return_tensors=\"pt\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<Tip>\n",
    "\n",
    "查阅[预处理](https://huggingface.co/docs/transformers/main/zh/./preprocessing)教程来获得有关分词的更详细的信息，以及如何使用 `AutoFeatureExtractor` 和 `AutoProcessor` 来处理图像，音频，还有多模式输入。\n",
    "\n",
    "</Tip>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### AutoModel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "🤗 Transformers 提供了一种简单统一的方式来加载预训练的实例. 这表示你可以像加载 `AutoTokenizer` 一样加载 `AutoModel`。唯一不同的地方是为你的任务选择正确的`AutoModel`。对于文本（或序列）分类，你应该加载`AutoModelForSequenceClassification`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoModelForSequenceClassification\n",
    "\n",
    "model_name = \"nlptown/bert-base-multilingual-uncased-sentiment\"\n",
    "pt_model = AutoModelForSequenceClassification.from_pretrained(model_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<Tip>\n",
    "\n",
    "通过 [任务摘要](https://huggingface.co/docs/transformers/main/zh/./task_summary) 查找 `AutoModel` 支持的任务.\n",
    "\n",
    "</Tip>\n",
    "\n",
    "现在可以把预处理好的输入批次直接送进模型。你只需要通过 `**` 来解包字典:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pt_outputs = pt_model(**pt_batch)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "模型在 `logits` 属性输出最终的激活结果. 在 `logits` 上应用 softmax 函数来查询概率:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.0021, 0.0018, 0.0115, 0.2121, 0.7725],\n",
       "        [0.2084, 0.1826, 0.1969, 0.1755, 0.2365]], grad_fn=<SoftmaxBackward0>)"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from torch import nn\n",
    "\n",
    "pt_predictions = nn.functional.softmax(pt_outputs.logits, dim=-1)\n",
    "print(pt_predictions)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<Tip>\n",
    "\n",
    "所有 🤗 Transformers 模型（PyTorch 或 TensorFlow）在最终的激活函数（比如 softmax）*之前* 输出张量，\n",
    "因为最终的激活函数常常与 loss 融合。模型的输出是特殊的数据类，所以它们的属性可以在 IDE 中被自动补全。模型的输出就像一个元组或字典（你可以通过整数、切片或字符串来索引它），在这种情况下，为 None 的属性会被忽略。\n",
    "\n",
    "</Tip>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 保存模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当你的模型微调完成，你就可以使用 [PreTrainedModel.save_pretrained()](https://huggingface.co/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.save_pretrained) 把它和它的分词器保存下来："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pt_save_directory = \"./pt_save_pretrained\"\n",
    "tokenizer.save_pretrained(pt_save_directory)\n",
    "pt_model.save_pretrained(pt_save_directory)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当你准备再次使用这个模型时，就可以使用 [PreTrainedModel.from_pretrained()](https://huggingface.co/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 加载它了："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pt_model = AutoModelForSequenceClassification.from_pretrained(\"./pt_save_pretrained\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 自定义模型构建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可以修改模型的配置类来改变模型的构建方式。配置指明了模型的属性，比如隐藏层或者注意力头的数量。当你从自定义的配置类初始化模型时，你就开始自定义模型构建了。模型属性是随机初始化的，你需要先训练模型，然后才能得到有意义的结果。\n",
    "\n",
    "通过导入 `AutoConfig` 来开始，之后加载你想修改的预训练模型。在 `AutoConfig.from_pretrained()` 中，你能够指定想要修改的属性，比如注意力头的数量："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoConfig\n",
    "\n",
    "my_config = AutoConfig.from_pretrained(\"distilbert/distilbert-base-uncased\", n_heads=12)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用 `AutoModel.from_config()` 根据你的自定义配置创建一个模型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoModel\n",
    "\n",
    "my_model = AutoModel.from_config(my_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "查阅 [创建一个自定义结构](https://huggingface.co/docs/transformers/main/zh/./create_a_model) 指南获取更多关于构建自定义配置的信息。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Trainer - PyTorch 优化训练循环"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "所有的模型都是标准的 [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)，所以你可以在任何典型的训练模型中使用它们。当你编写自己的训练循环时，🤗 Transformers 为 PyTorch 提供了一个 `Trainer` 类，它包含了基础的训练循环并且为诸如分布式训练，混合精度等特性增加了额外的功能。\n",
    "\n",
    "取决于你的任务, 你通常可以传递以下的参数给 `Trainer`：\n",
    "\n",
    "1. [PreTrainedModel](https://huggingface.co/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel) 或者 [`torch.nn.Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)：\n",
    "\n",
    "   ```py\n",
    "   >>> from transformers import AutoModelForSequenceClassification\n",
    "\n",
    "   >>> model = AutoModelForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n",
    "   ```\n",
    "\n",
    "2. `TrainingArguments` 含有你可以修改的模型超参数，比如学习率，批次大小和训练时的迭代次数。如果你没有指定训练参数，那么它会使用默认值：\n",
    "\n",
    "   ```py\n",
    "   >>> from transformers import TrainingArguments\n",
    "\n",
    "   >>> training_args = TrainingArguments(\n",
    "   ...     output_dir=\"path/to/save/folder/\",\n",
    "   ...     learning_rate=2e-5,\n",
    "   ...     per_device_train_batch_size=8,\n",
    "   ...     per_device_eval_batch_size=8,\n",
    "   ...     num_train_epochs=2,\n",
    "   ... )\n",
    "   ```\n",
    "\n",
    "3. 一个预处理类，比如分词器，特征提取器或者处理器：\n",
    "\n",
    "   ```py\n",
    "   >>> from transformers import AutoTokenizer\n",
    "\n",
    "   >>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n",
    "   ```\n",
    "\n",
    "4. 加载一个数据集：\n",
    "\n",
    "   ```py\n",
    "   >>> from datasets import load_dataset\n",
    "\n",
    "   >>> dataset = load_dataset(\"rotten_tomatoes\")  # doctest: +IGNORE_RESULT\n",
    "   ```\n",
    "\n",
    "5. 创建一个给数据集分词的函数，并且使用 `map` 应用到整个数据集：\n",
    "\n",
    "   ```py\n",
    "   >>> def tokenize_dataset(dataset):\n",
    "   ...     return tokenizer(dataset[\"text\"])\n",
    "\n",
    "   >>> dataset = dataset.map(tokenize_dataset, batched=True)\n",
    "   ```\n",
    "\n",
    "6. 用来从数据集中创建批次的 [DataCollatorWithPadding](https://huggingface.co/docs/transformers/main/zh/main_classes/data_collator#transformers.DataCollatorWithPadding)：\n",
    "\n",
    "   ```py\n",
    "   >>> from transformers import DataCollatorWithPadding\n",
    "\n",
    "   >>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)\n",
    "   ```\n",
    "\n",
    "现在把所有的类传给 `Trainer`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import Trainer\n",
    "\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=training_args,\n",
    "    train_dataset=dataset[\"train\"],\n",
    "    eval_dataset=dataset[\"test\"],\n",
    "    processing_class=tokenizer,\n",
    "    data_collator=data_collator,\n",
    ")  # doctest: +SKIP"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一切准备就绪后，调用 `train()` 进行训练："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<Tip>\n",
    "\n",
    "对于像翻译或摘要这些使用序列到序列模型的任务，用 `Seq2SeqTrainer` 和 `Seq2SeqTrainingArguments` 来替代。\n",
    "\n",
    "</Tip>\n",
    "\n",
    "你可以通过子类化 `Trainer` 中的方法来自定义训练循环。这样你就可以自定义像损失函数，优化器和调度器这样的特性。查阅 `Trainer` 参考手册了解哪些方法能够被子类化。\n",
    "\n",
    "另一个自定义训练循环的方式是通过[回调](https://huggingface.co/docs/transformers/main/zh/./main_classes/callback)。你可以使用回调来与其他库集成，查看训练循环来报告进度或提前结束训练。回调不会修改训练循环。如果想自定义损失函数等，就需要子类化 `Trainer` 了。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用 Tensorflow 训练"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "所有模型都是标准的 [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model)，所以你可以通过 [Keras](https://keras.io/) API 实现在 Tensorflow 中训练。🤗 Transformers 提供了 `~TFPreTrainedModel.prepare_tf_dataset` 方法来轻松地将数据集加载为 `tf.data.Dataset`，这样你就可以使用 Keras 的 [`compile`](https://keras.io/api/models/model_training_apis/#compile-method) 和 [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) 方法马上开始训练。\n",
    "\n",
    "1. 使用 `TFPreTrainedModel` 或者 [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) 来开始：\n",
    "\n",
    "   ```py\n",
    "   >>> from transformers import TFAutoModelForSequenceClassification\n",
    "\n",
    "   >>> model = TFAutoModelForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n",
    "   ```\n",
    "\n",
    "2. 一个预处理类，比如分词器，特征提取器或者处理器：\n",
    "\n",
    "   ```py\n",
    "   >>> from transformers import AutoTokenizer\n",
    "\n",
    "   >>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n",
    "   ```\n",
    "\n",
    "3. 创建一个给数据集分词的函数\n",
    "\n",
    "   ```py\n",
    "   >>> def tokenize_dataset(dataset):\n",
    "   ...     return tokenizer(dataset[\"text\"])  # doctest: +SKIP\n",
    "   ```\n",
    "\n",
    "4. 使用 `map` 将分词器应用到整个数据集，之后将数据集和分词器传给 `~TFPreTrainedModel.prepare_tf_dataset`。如果你需要的话，也可以在这里改变批次大小和是否打乱数据集：\n",
    "\n",
    "   ```py\n",
    "   >>> dataset = dataset.map(tokenize_dataset)  # doctest: +SKIP\n",
    "   >>> tf_dataset = model.prepare_tf_dataset(\n",
    "   ...     dataset, batch_size=16, shuffle=True, tokenizer=tokenizer\n",
    "   ... )  # doctest: +SKIP\n",
    "   ```\n",
    "\n",
    "5. 一切准备就绪后，调用 `compile` 和 `fit` 开始训练：\n",
    "\n",
    "   ```py\n",
    "   >>> from tensorflow.keras.optimizers import Adam\n",
    "\n",
    "   >>> model.compile(optimizer=Adam(3e-5))\n",
    "   >>> model.fit(dataset)  # doctest: +SKIP\n",
    "   ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 接下来做什么?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在你已经完成了 🤗 Transformers 的快速上手教程，来看看我们的指南并且学习如何做一些更具体的事情，比如写一个自定义模型，为某个任务微调一个模型以及如何使用脚本来训练模型。如果你有兴趣了解更多 🤗 Transformers 的核心章节，那就喝杯咖啡然后来看看我们的概念指南吧！"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
